package com.pilipala.service.Impl;

import com.pilipala.constant.CodeConstant;
import com.pilipala.constant.LoginConstant;
import com.pilipala.dto.CodeDTO;
import com.pilipala.exception.EmailException;
import com.pilipala.properties.MailProperty;
import com.pilipala.service.CodeService;
import com.pilipala.utils.CodeUtil;
import com.pilipala.utils.EmailUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.validator.routines.EmailValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class CodeServiceImpl implements CodeService {

    @Autowired
    private EmailUtil emailUtil;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private EmailValidator emailValidator;

    @Autowired
    private MailProperty mailProperty;

    @Override
    public void sendCode(CodeDTO codeDTO) {
        String email = codeDTO.getEmail();
        if (!emailValidator.isValid(email)){
//            邮箱不合法
            throw new EmailException(LoginConstant.EMAIL_IS_NOT_VALID);
        }
//        邮箱合法
//        生成验证码
        String code = CodeUtil.generateNumberCode();
//        发送验证码给用户
        emailUtil.send(mailProperty,email,CodeConstant.SEND_TEXT + code,CodeConstant.CODE_NAME);
//        存到redis当中方便后续验证
        redisTemplate.opsForValue().set("email:"+email,code, CodeConstant.ENTRY_TTL, TimeUnit.MINUTES);
    }
}





